#/usr/bin/env python
# coding:utf-8

import paramiko
import smtplib
from email.mime.text import MIMEText

#定义要监控的服务端口
dist_port_set = {'22', '8080', '8081'}

#定义发送邮件类
class SendEMail(object):
    # 定义第三方 SMTP 服务
    def __init__(self):
        self.mail_host = "smtp.163.com"  # SMTP服务器
        self.mail_user = "xxx@163.com"  # 用户名
        self.mail_pass = "xxx"  # 密码
        self.sender = 'xxx@163.com'  # 发件人邮箱
        #启用SSL发信
        self.smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
        self.smtpObj.login(self.mail_user, self.mail_pass)  # 登录验证

    def sendmail(self, receivers, title, content):
        message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
        message['From'] = "{}".format(self.sender)
        #相当于把列表转换为字符串    如my_list=['a','b']  ",".join(my_list)  结果为"a,b"
        message['To'] = ",".join(receivers)
        message['Subject'] = title
        try:
            #发送message的时候就会带上标题及发送内容
            self.smtpObj.sendmail(self.sender, message['To'].split(','), message.as_string())  # 发送
            print("mail has been send successfully.")
        except smtplib.SMTPException as e:
            print(e)

#定义检测服务端口函数
def checkport():
    client = paramiko.SSHClient()
    # 自动添加策略，保存服务器主机名和密钥信息
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect("192.168.0.105", username="root", password="xxx")
    #pl = psutil.pids()
    cmd = "netstat -lnpt  |awk -F: '{print $2}'|sed '/^$/d' |awk '{print $1}'"
    stdin, stdout, stderr = client.exec_command(cmd)
    pl = stdout.readlines()
    client.close()
    server_port_set = set()
    for port in pl:
        server_port_set.add(port.strip())
    print(server_port_set)
    #打印出dist_port_set有的但是server_port_set里没有的
    down_port_set = dist_port_set.difference(server_port_set)
    return down_port_set


down_port_set = checkport()
if len(down_port_set) > 0 :
    print("{0}端口不存在,发送邮件".format(down_port_set))
    sm = SendEMail()
    sm.sendmail(['xxx@qq.com'], "{0}端口down了".format(down_port_set), "{0}端口down了,请检查原因".format(down_port_set))

